package com.zzz.oauth2;

import com.zzz.security.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @author Chunsheng.Zhang
 * @date 2021/5/12 10:48
 * @description : 授权服务
 */
@Configuration
@EnableAuthorizationServer//表示开启授权服务
public class AuthorizationServiceConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private RedisConnectionFactory factory;

    @Autowired
    private AuthenticationManager manager;




    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //第三方应用的id：client_id
                .withClient("zcs")
                //第三方应用的密码：client_secret
                .secret("$2a$10$oYZt.IShCnZ8HzXNtFvqJelli3U8vxS/wEj5wDwovRlinKrzGVtL.")
                //授权同意的类型(这里只允许密码授权)
                .authorizedGrantTypes("password","refresh_token")
                //有效时间
                .accessTokenValiditySeconds(1800)
                .refreshTokenValiditySeconds(7200)
                .resourceIds("rid")
                //作用域，范围
                .scopes("all");
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(new RedisTokenStore(factory))
                //身份验证管理
                .authenticationManager(manager)
                .userDetailsService(customUserDetailsService);
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许客户端表单身份验证
        security.allowFormAuthenticationForClients();

    }
}
